<!-- 角色权限分配弹窗 -->
<template>
  <ele-modal
    :width="460"
    title="绑定仓库"
    position="center"
    :model-value="modelValue"
    :body-style="{ padding: '12px 0 12px 22px' }"
    @update:model-value="updateModelValue"
  >
    <ele-loading
      :loading="listLoading"
      :style="{
        height: '560px',
        paddingRight: '22px',
        maxHeight: 'calc(100vh - 192px)',
        minHeight: '100px',
        overflow: 'auto',
      }"
    >
      <el-checkbox-group v-model="checkedIds" class="checkbox-list">
        <div v-for="item in warehouseList" :key="item.id" class="checkbox-item">
          <el-checkbox :label="item.name" :value="item.id" />
        </div>
      </el-checkbox-group>
    </ele-loading>
    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
import { listWarehouse } from '@/api/common'
import { banWarehouse } from '@/api/mch-system/user'

const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 当前角色数据 */
  data: {
    default: () => { },
    type: Object,
  },
  type: Number,
})

const emit = defineEmits(['update:modelValue', 'done'])

const checkedIds = ref([])

/** 权限数据 */
const warehouseList = ref([])

/** 权限数据请求状态 */
const listLoading = ref(false)

/** 提交状态 */
const loading = ref(false)

/** 查询权限数据 */
function query() {
  listLoading.value = true
  listWarehouse({ type: 1 })
    .then((res) => {
      warehouseList.value = res.data
    })
    .finally(() => {
      listLoading.value = false
    })
}

/** 保存权限分配 */
function save() {
  loading.value = true
  banWarehouse(props.data.id, checkedIds.value, props.type)
    .then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        updateModelValue(false)
        emit('done')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      checkedIds.value = [...props.data.warehouse_ids ?? []]
      query()
    }
  },
)
</script>

<style lang="scss" scoped>
.checkbox-list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.checkbox-item {
  margin: 5px 10px;
}
</style>
